import { ref } from 'vue';
import { defineStore } from 'pinia';

export const useRechargeStore = defineStore('recharge', () => {
  // 状态
  const userBalance = ref(0);
  const rechargeHistory = ref([]);
  const loading = ref(false);
  const error = ref(null);

  // 模拟获取用户余额
  const fetchUserBalance = async () => {
    loading.value = true;
    error.value = null;
    try {
      // 在实际项目中，这里应该是一个API调用
      // 模拟网络请求延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 模拟数据 - 实际项目中应该从API获取
      userBalance.value = 128.50;
      
    } catch (err) {
      console.error('获取余额失败:', err);
      error.value = '获取余额失败，请稍后重试';
    } finally {
      loading.value = false;
    }
  };

  // 模拟充值操作
  const recharge = async (amount, totalAmount, paymentMethod, coupon) => {
    loading.value = true;
    error.value = null;
    try {
      // 在实际项目中，这里应该是一个API调用
      // 模拟网络请求延迟
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 模拟充值成功
      const newBalance = userBalance.value + totalAmount;
      userBalance.value = newBalance;
      
      // 添加到充值历史
      const rechargeRecord = {
        id: Date.now(),
        amount: amount,
        totalAmount: totalAmount,
        paymentMethod: paymentMethod,
        coupon: coupon,
        date: new Date(),
        status: 'success'
      };
      
      rechargeHistory.value.unshift(rechargeRecord);
      
      // 在实际项目中，这里应该将数据保存到后端
      console.log('充值成功:', rechargeRecord);
      
      return rechargeRecord;
      
    } catch (err) {
      console.error('充值失败:', err);
      error.value = '充值失败，请稍后重试';
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 获取充值历史
  const fetchRechargeHistory = async () => {
    loading.value = true;
    error.value = null;
    try {
      // 在实际项目中，这里应该是一个API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 模拟历史数据
      rechargeHistory.value = [
        {
          id: 1,
          amount: 100,
          totalAmount: 115,
          paymentMethod: 'alipay',
          coupon: null,
          date: new Date('2024-01-15'),
          status: 'success'
        },
        {
          id: 2,
          amount: 50,
          totalAmount: 55,
          paymentMethod: 'wechat',
          coupon: { id: 1, name: '新用户专享', discount: 9 },
          date: new Date('2024-01-10'),
          status: 'success'
        }
      ];
      
    } catch (err) {
      console.error('获取充值历史失败:', err);
      error.value = '获取充值历史失败，请稍后重试';
    } finally {
      loading.value = false;
    }
  };

  // 格式化支付方式显示
  const formatPaymentMethod = (method) => {
    const methods = {
      'alipay': '支付宝',
      'wechat': '微信支付',
      'creditcard': '银行卡',
      'unionpay': '银联云闪付'
    };
    return methods[method] || method;
  };

  return {
    userBalance,
    rechargeHistory,
    loading,
    error,
    fetchUserBalance,
    recharge,
    fetchRechargeHistory,
    formatPaymentMethod
  };
});